package cn.bitkit.mybatis.builder;

import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import cn.bitkit.base.exception.BusinessAssert;
import cn.bitkit.mybatis.base.BaseSqlBuilder;
import cn.bitkit.mybatis.entity.EntityClass;

/**
 * @author changbo
 */
public class InsertListBuilder implements BaseSqlBuilder {

	@Override
	public String build(EntityClass entityClass, Map<String, Object> paramMap) {
		StringJoiner sql = new StringJoiner(" \n");
		sql.add("INSERT INTO "+ entityClass.getTableName());
		sql.add("(" + entityClass.getSqlColumns() + ")");
		sql.add("VALUES");
		sql.add(initList(entityClass, paramMap));
        return sql.toString();
	}
	
	@SuppressWarnings("unchecked")
	private String initList(EntityClass entityClass, Map<String, Object> map) {
		List<Object> list = (List<Object>) (map.get("list"));
		BusinessAssert.isNotEmpty(list, "param[list] can not be empty");
		//所有字段取值
		String values = entityClass.getFieldList().stream()
				.map(e -> "#{list[entity_index]." + e.getField() + "}")
				.collect(Collectors.joining(",", "(", ")"));
		AtomicInteger index = new AtomicInteger(0);
        return list.stream()
            .map(e -> values.replaceAll("entity_index", "" + index.getAndIncrement()))
            .collect(Collectors.joining(","));
	}

}
